package com.dominator.utils.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dominFramework.core.id.SystemIdUtils;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.JsonUtils;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.mybatis.dao.T_adminPO;
import com.dominator.mybatis.dao.T_merchantPO;
import com.dominator.mybatis.dao.T_userPO;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.encode.Des3Utils;
import com.dominator.utils.encode.MD5;
import com.dominator.utils.encode.MerchantAESUtil;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.system.Constants;
import com.dominator.utils.system.PropertiesLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * api 工具类
 *
 * @author dl
 */
public class ApiUtils {
    public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");
    //sentine
    //private static final RedisSentinelUtils ru = RedisSentinelUtils.getRu();

    //single
    private static RedisUtil ru = RedisUtil.getRu();


    private static final Logger log = LoggerFactory.getLogger(ApiUtils.class);


    /**
     * 根据用户名获取token
     *
     * @param
     * @return
     */
    public static String getTokenByUserPO(T_userPO userPO) throws ApiException {
        if (SystemUtils.isEmpty(userPO)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String dateStr = sdf.format(new Date());
        String enc = MD5.GetMD5Code(String.format("%s_%s", userPO.getPhone_num(), dateStr));
        Dto tokenDto=Dtos.newDto();
        tokenDto.put("phoneNum",userPO.getPhone_num());
        tokenDto.put("id",userPO.getId());
        String result = ru.setObjectEx(enc,userPO.toDto(),Constants.TOKEN_TIMES_INT);
        System.out.println("token放redis" + result);
        return enc;
    }





    /**
     * token检查
     * @param token
     * @return
     */
    public static boolean checkToken(String phoneNum, String token) throws ApiException {
        log.info("checktoken");
        if (!Constants.TOKEN_CHECK) {
            return true;
        }
        if (SystemUtils.isEmpty(phoneNum)||SystemUtils.isEmpty(token)) {
            throw new ApiException(ReqEnums.REQ_TOKEN_FALSE);
        }
        //校验合法性
        Dto dto=(Dto)ru.getObject(token);
        if (SystemUtils.isEmpty(dto)){
            throw new  ApiException(ReqEnums.REQ_TOKEN_FALSE);
        }
        if (phoneNum.equals(dto.getString("phone_num"))) {
            ru.setObjectEx(token,dto,Constants.TOKEN_TIMES_INT);
        }else {
        }
        return true;
    }


    /**
     * 生成随机数字和字母组合
     *
     * @param length
     * @return
     */
    public static String getCharAndNumr(int length) {
        String a = "1345678abcdefghkmnoprstuvwxyABCDEFGHKMNPRSTUVWXY";
        char[] rands = new char[length];
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < rands.length; i++)
        {
            int rand = (int) (Math.random() * a.length());
            rands[i] = a.charAt(rand);
        }
        for(int i=0;i<rands.length;i++){
            sb.append(rands[i]);
        }

        return sb.toString().toUpperCase();
    }




    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 校验名字合法
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isName(String str) {
        return str.matches("^[\u4e00-\u9fa5]{1,20}?$");

    }


    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    //设置x个随机组成的数
    public static String CreateRandom(int x) {
        //随机数
        Random r = new Random();
        String R = "";
        for (int i = 0; i < x; i++) {
            R = R + r.nextInt(10);
        }
        return R;
    }


    public static boolean checkFixTime(ServletResponse response) {
        String fixTime = propertiesLoader.getProperty("fix_time");
        try {
            response.setContentType("text/json; charset=utf-8");
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            Date tmBegin = sdf.parse(fixTime.split("-")[0]);
            Date tmEnd = sdf.parse(fixTime.split("-")[1]);
            Date dt = new Date();
            Date now = sdf.parse(String.format("%s:%s", dt.getHours(), dt.getMinutes()));
            if (now.getTime() >= tmBegin.getTime() && now.getTime() < tmEnd.getTime()) {
                response.getWriter().print("{\"code\":\"401\",\"message\":\"系统维护中,暂停服务\"}");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            log.error(String.format("维护时间配置错误：%s。\n%s", fixTime, e.getMessage()));
            e.printStackTrace();
        }
        return true;
    }

    public static void checkParam(Dto dto, String params) throws ApiException {
        if (SystemUtils.isEmpty(params)) {
            throw new ApiException(ReqEnums.REQ_PARAM_ERROR.getCode(), "参数为空," + params);
        }
        String[] paramArr = params.split(",");
        for (int i = 0; i < paramArr.length; i++) {
            if (SystemUtils.isEmpty(dto.getString(paramArr[i].trim()))) {
                throw new ApiException(ReqEnums.REQ_PARAM_ERROR.getCode(), "参数(" + paramArr[i] + ")为空,");
            }
        }
    }


    public static String getOrderIdByUUId() {
        int machineId = 1;//最大支持1-9个集群机器部署
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if(hashCodeV < 0) {//有可能是负数
            hashCodeV = - hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        return machineId + String.format("%015d", hashCodeV);
    }


    /**
     * 计算手续费
     * @param money
     * @return
     */
    public static BigDecimal subPoundage(BigDecimal money){
        if (money.compareTo(new BigDecimal(1000))<=0){
           return  money.subtract(BigDecimal.ONE);
        }else if (money.compareTo(new BigDecimal(2500))<=0){
            return  money.multiply(new BigDecimal(0.999)).setScale(2,RoundingMode.FLOOR);
        }else {
            return  money.subtract(new BigDecimal(25));
        }
    }

    /**
     * 判断是否是redis-set的元素
     * @param setName
     * @param value
     * @return
     */
    public static Boolean isMember(String setName,String value){
        return ru.sismember(setName,value);
    }




    public static Date getNextYear(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        date = calendar.getTime();
        System.out.println(date);
        return date;
    }


    public static boolean isIncludeMobile(String str){
        Pattern p = Pattern.compile("^1(3|5|7|8|4|6)\\d{9}");
        Matcher m = p.matcher(str);
        return m.matches();
    }



   public static String setObject(String key,Object object){
        return ru.setObject(key, object);
   }




    public static void main(String[] args) {

        System.out.println(SystemIdUtils.uuid());

    }
}
